package lei.n_JSON_Map_JsonString_对象的之间转换;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.ParserConfig;
import lei.g_java数组.排序.Students;


import java.util.*;

/**
 * @className: JSON之间的转换
 * @author: xl
 * @date: 2025/7/26 09:32
 * @Version: 1.0
 * @description:
 */

public class AAmain_JSON之间的转换 {

    public static void main(String[] args) {

        // 这个错误是由于FastJSON在ASM模式下生成字节码时出现UTF-8编码问题导致的。以下是几种修复方案：
        // 禁用ASM优化来避免UTF-8字符串常量池错误
        ParserConfig.getGlobalInstance().setAsmEnable(false);

        //1、String转JSON
        String str = "{\"name\":\"dsad\",\"age\":\"123\",\"score\":\"1000\"}";
        JSONObject json = JSONObject.parseObject(str);

        //2、StringJSON格式转Map
        Map<String, Object> map1 = JSON.parseObject(str);
        System.out.println(map1);

        //5、String转对象
        Students students = JSON.parseObject(str, Students.class);
        System.out.println(students);




        //3、Map转JSON
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("a", "a");
        map2.put("b", "123");
        JSONObject json1 = new JSONObject(map2);


        //4、Map转String
        Map<String, Object> map3 = new HashMap<>();
        map3.put("a", "b");
        String s = JSONObject.toJSONString(map3);


        //5、JSON转String
        JSONObject json6 = new JSONObject();
        json.put("c", "v");
        json.put("z", "123n");

        json6.toJSONString();


        //6、JSON转Map
        JSONObject json2 = new JSONObject();
        json2.put("ccc", "321");
        json2.put("bbb", "123");

        // 使用 getInnerMap() 方法或者直接使用 JSONObject 的 entrySet
        Map<String, Object> map4 = json2.getInnerMap(); // 方式1
        // 或者
        Map<String, Object> map5 = new HashMap<>(json2); // 方式2



        //7、将Json格式的字符串转换为对象
        AlertRule alertRule2 = JSON.parseObject("{\"diffAbs\":{\"upper\":2000,\"lower\":23000},\"diffPercent\":{\"upper\":2000,\"lower\":23000},\"relation\":\"OR\"}", AlertRule.class);
        System.out.println(alertRule2.getDiffAbs());


        //8、将map转换为对象

        Map<String, String> mapObject = new HashMap<>();
        mapObject.put("studens", "{\"city\":{\"School\":\"san\",\"studen\":[\"1\",\"2\",\"3\"]}}"); // 注意这里修改了数组元素为字符串
        // 修复变量名错误：map -> mapObject
        Map<String, Peopler> student = JSON.parseObject(mapObject.get("studens"), new TypeReference<Map<String, Peopler>>() {
        });
        System.out.println(student);
        Set<Map.Entry<String, Peopler>> entries = student.entrySet();
        for (Map.Entry<String, Peopler> aa : entries) {
            System.out.println(aa);
            Peopler value = aa.getValue();
            String school = value.getSchool();
            System.out.println(school);
            List<String> studet = value.getStuden();
            System.out.println(studet);
        }
    }


}




